import { createPersistStore, BaseState } from './index'
import { nanoid } from 'nanoid'

// 消息发送者类型
export type MessageSender = 'user' | 'ai';

// 消息状态
export type MessageStatus = 'sending' | 'sent' | 'error';

// 附件类型
export type AttachmentType = 'chapter' | 'character' | 'image' | 'text';

// 附件接口
export interface Attachment {
  id: string;
  type: AttachmentType;
  name: string;
  content: any;
  previewText?: string;
}

// 消息接口
export interface Message {
  id: string;
  conversationId: string;
  content: string;
  sender: MessageSender;
  status: MessageStatus;
  attachments: Attachment[];
  createdAt: string;
  updatedAt: string;
}

// 对话接口
export interface Conversation {
  id: string;
  projectId: string;
  title: string;
  messages: Message[];
  createdAt: string;
  updatedAt: string;
  userAttachments?: Attachment[]; // 临时存储用户添加但尚未发送的附件
}

// AI助手状态接口
interface AIAssistantState extends BaseState {
  conversations: Conversation[];
  currentConversation: Conversation | null;
  isSending: boolean;
  
  // 操作函数
  fetchConversations: (projectId: string) => Promise<Conversation[]>;
  createConversation: (projectId: string, title: string) => Promise<Conversation>;
  deleteConversation: (id: string) => Promise<void>;
  selectConversation: (id: string) => void;
  
  addMessage: (content: string, attachments?: Attachment[]) => Promise<void>;
  generateAIResponse: () => Promise<void>;
  addAttachment: (attachment: Attachment) => void;
  removeAttachment: (attachmentId: string) => void;
}

// 初始状态
const initialState = {
  conversations: [],
  currentConversation: null,
  isLoading: false,
  isSending: false,
  error: null
}

export const useAIAssistantStore = createPersistStore<AIAssistantState>(
  'ai-assistant',
  initialState as any,
  (set, get) => ({
    ...initialState,
    
    fetchConversations: async (projectId) => {
      set({ isLoading: true, error: null });
      
      try {
        // 在实际实现中，这里会从API或本地存储获取数据
        // 现在我们使用存储在Zustand中的数据
        await new Promise(resolve => setTimeout(resolve, 300));
        const conversations = get().conversations.filter(c => c.projectId === projectId);
        set({ isLoading: false });
        return conversations;
      } catch (error) {
        set({ error: String(error), isLoading: false });
        throw error;
      }
    },
    
    createConversation: async (projectId, title) => {
      const now = new Date().toISOString();
      const newConversation: Conversation = {
        id: nanoid(),
        projectId,
        title,
        messages: [],
        createdAt: now,
        updatedAt: now,
        userAttachments: []
      };
      
      set(state => ({ 
        conversations: [...state.conversations, newConversation],
        currentConversation: newConversation
      }));
      
      return newConversation;
    },
    
    deleteConversation: async (id) => {
      set(state => {
        const conversations = state.conversations.filter(c => c.id !== id);
        const currentConversation = state.currentConversation?.id === id
          ? null
          : state.currentConversation;
          
        return { conversations, currentConversation };
      });
    },
    
    selectConversation: (id) => {
      const { conversations } = get();
      const conversation = conversations.find(c => c.id === id) || null;
      set({ currentConversation: conversation });
    },
    
    addMessage: async (content, attachments = []) => {
      const { currentConversation } = get();
      if (!currentConversation) return;
      
      set({ isSending: true });
      
      try {
        const now = new Date().toISOString();
        const newMessage: Message = {
          id: nanoid(),
          conversationId: currentConversation.id,
          content,
          sender: 'user',
          status: 'sent',
          attachments,
          createdAt: now,
          updatedAt: now
        };
        
        // 更新当前对话的消息列表
        set(state => {
          const updatedConversation = {
            ...state.currentConversation!,
            messages: [...state.currentConversation!.messages, newMessage],
            updatedAt: now
          };
          
          // 更新对话列表中的当前对话
          const conversations = state.conversations.map(c => 
            c.id === updatedConversation.id ? updatedConversation : c
          );
          
          return {
            conversations,
            currentConversation: updatedConversation,
            isSending: false
          };
        });
        
        // 生成AI响应
        await get().generateAIResponse();
      } catch (error) {
        set({ error: String(error), isSending: false });
      }
    },
    
    generateAIResponse: async () => {
      const { currentConversation } = get();
      if (!currentConversation) return;
      
      set({ isSending: true });
      
      try {
        // 这里会调用AI服务生成响应
        // 现在暂时用模拟响应
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // 根据最后一条用户消息生成响应
        const lastUserMessage = [...currentConversation.messages]
          .reverse()
          .find(m => m.sender === 'user');
          
        let aiContent = '我是AI助手，有什么可以帮到您的？';
        
        if (lastUserMessage) {
          const userContent = lastUserMessage.content.toLowerCase();
          
          if (userContent.includes('描写') || userContent.includes('场景')) {
            aiContent = '以下是一个更加丰富的场景描写示例：\n\n'
              + '黄昏的光芒斜射进古老的图书馆，灰尘在光束中缓缓舞动，如同时间的碎片。书架高耸至天花板，木质的纹理讲述着数百年的故事。空气中弥漫着羊皮纸、墨水和历史的气息，窗外枝桠摇曳的影子在地板上投下斑驳的花纹，仿佛是另一个世界的生物在墙壁上游走。角落里的老座钟滴答作响，每一声都像是对永恒的轻声低语。';
          } else if (userContent.includes('对话') || userContent.includes('人物')) {
            aiContent = '这是一段更有特色的角色对话示例：\n\n'
              + '"你总是这样，不是吗？"莉亚将茶杯重重放在桌上，液体溅出边缘。\n\n'
              + '马克斯叹了口气，手指无意识地敲击着桌面。"具体指什么？我的谨慎还是我的犹豫？"\n\n'
              + '"两者都是，"她直视着他的眼睛，"但主要是你那种明知问题所在却假装一切正常的态度。"\n\n'
              + '他停下了敲击，室内突然安静得令人不安。"有时候，"他最终开口，声音低沉，"面对某些真相需要的不是勇气，而是时机。"';
          } else if (userContent.includes('情节') || userContent.includes('故事')) {
            aiContent = '以下是一个可能的故事情节转折：\n\n'
              + '当艾伦终于找到传说中的水晶洞穴时，他惊讶地发现洞口已经有人先行一步。地上的脚印还很新鲜，通向洞穴深处。更令他不安的是，这些脚印的形状与他熟悉的任何生物都不相同。随着他深入洞穴，墙壁上的古老符文开始发光，仿佛回应着什么人的召唤。突然，一阵微弱的笑声从黑暗中传来，他认出了这个声音——它属于他五年前在那场大火中supposedly已经死去的妹妹。';
          } else {
            aiContent = '感谢您的提问。作为AI写作助手，我可以帮助您：\n\n'
              + '• 丰富场景描写和环境细节\n'
              + '• 发展人物性格和背景故事\n'
              + '• 构建合理且引人入胜的情节\n'
              + '• 改进对话，使其更自然且富有个性\n'
              + '• 提供不同文体和风格的写作建议\n\n'
              + '请详细描述您需要帮助的具体方面，我会针对性地提供建议。';
          }
          
          // 如果有附件，添加参考信息
          if (lastUserMessage.attachments.length > 0) {
            aiContent += '\n\n我参考了您提供的内容生成了回复。';
          }
        }
        
        const now = new Date().toISOString();
        const newMessage: Message = {
          id: nanoid(),
          conversationId: currentConversation.id,
          content: aiContent,
          sender: 'ai',
          status: 'sent',
          attachments: [],
          createdAt: now,
          updatedAt: now
        };
        
        // 更新当前对话的消息列表
        set(state => {
          const updatedConversation = {
            ...state.currentConversation!,
            messages: [...state.currentConversation!.messages, newMessage],
            updatedAt: now
          };
          
          // 更新对话列表中的当前对话
          const conversations = state.conversations.map(c => 
            c.id === updatedConversation.id ? updatedConversation : c
          );
          
          return {
            conversations,
            currentConversation: updatedConversation,
            isSending: false
          };
        });
      } catch (error) {
        set({ error: String(error), isSending: false });
      }
    },
    
    addAttachment: (attachment) => {
      const { currentConversation } = get();
      if (!currentConversation) return;
      
      // 这里我们不添加到任何消息中，而是暂存等待用户发送消息
      // 通常会有一个临时区域显示用户添加的附件
      set(state => {
        const updatedConversation = {
          ...state.currentConversation!,
          userAttachments: [
            ...(state.currentConversation!.userAttachments || []),
            attachment
          ]
        };
        
        const conversations = state.conversations.map(c => 
          c.id === updatedConversation.id ? updatedConversation : c
        );
        
        return {
          conversations,
          currentConversation: updatedConversation
        };
      });
    },
    
    removeAttachment: (attachmentId) => {
      const { currentConversation } = get();
      if (!currentConversation || !currentConversation.userAttachments) return;
      
      set(state => {
        const updatedConversation = {
          ...state.currentConversation!,
          userAttachments: state.currentConversation!.userAttachments!.filter(
            (a: Attachment) => a.id !== attachmentId
          )
        };
        
        const conversations = state.conversations.map(c => 
          c.id === updatedConversation.id ? updatedConversation : c
        );
        
        return {
          conversations,
          currentConversation: updatedConversation
        };
      });
    }
  })
); 